<?php

/**
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:    modifier
 * Name:    filesize
 * Version: 0.1
 * Date:    2003-02-21
 * Author:  Joscha Feth, joscha@feth.com
 * Purpose: formats a filesize (in bytes) to human-readable format
 * Usage:   In the template, use
            {$filesize|fsize_format}        =>    123.45 B|KB|MB|GB|TB
            or
            {$filesize|fsize_format:"MB"}   =>    123.45 MB
            or
            {$filesize|fsize_format:"TB":4} =>    0.0012 TB
 * Params:
            int         size        the filesize in bytes
            string      format      the format, the output shall be: B, KB, MB, GB or TB
            int         precision   the rounding precision
 * Install: Drop into the plugin directory
 * -------------------------------------------------------------
 */
function smarty_modifier_filesize($size, $format = '', $precision = 2) {
    $format = strtoupper($format);
    $sizes = array(
        'TB' => 1099511627776,
        'GB' => 1073741824,
        'MB' => 1048576,
        'KB' => 1024,
        'B'  => 0,
    );
    foreach ($sizes as $unit => $bytes) {
        if ($size >= $bytes || $unit == $format) {
            return round($size / max($bytes, 1), $precision) . ' ' . $unit;
        }
    }
}
